import json
from django.shortcuts import render
import re
from django.http import JsonResponse
from django.views import View
from appAdminUseClassroom_new.models import ClassroomuseinfoIf, Classroombasicinfo, ClassroomuseinfoWaiyu,ClassroomuseinfoJidian,ClassroomuseinfoJingguan,Building
from .models import Reserve

'''为了方便多选空闲教室，采用layui自带的toolbar添加复选框，获取多选框的id等具体代码请参考layui官网
    为了方便渲染和获取复选框信息，放弃了layui的静态表格渲染，使用方法渲染
    只修改了教室预约界面的代码，学生预约的界面请自行复制粘贴
'''

num_entry = 100    #为了提升渲染的速度，只向前端传递100条数据

#最开始将页面定位到教师预约界面
def  admin_useInfo_new (request):
    return render(request,"teacher_reserve.html")

def judgeNone(s):#判断管理员是否选择了该条件，要是选择了，则查询对应条件的教室，要是没有选择，就默认该条件下所有情况都显示出来
    if s != None:
        return int(s)
    else:
        return 0

#查找符合预约条件的教室，因为楼栋表是分开的，为了方便，必须选择楼栋，其他的条件可以选也可以不选，
#不选就意味着所有符合这个条件的教室都被查找出来
#为了方便前端layui的渲染，返回给前端的是json类型的数据
def search_useInfo_new(request):
    uid = request.session['uid']
    # 检错
    try:
        building = judgeNone(request.POST["building"])
        floor = judgeNone(request.POST["floor"])
        room = judgeNone(request.POST["room"])
        week = judgeNone(request.POST.get('week'))
        day = judgeNone(request.POST.get('day'))
        time = judgeNone(request.POST.get('time'))
        state = judgeNone(request.POST.get('state'))
        print(building,floor,room,week,day,time,state)
    except:
        return JsonResponse({"flag": "输入出错"})
    classroom_list = []
    # 查询
    try:
        #动态组合查询
        kwargs={}
        ccs = Classroombasicinfo.objects.filter(building_id=building).all()
        if floor != 0 and room != 0: #选择了教室
            for cc in ccs:
                if cc.classroom_name == floor*100 + room:
                    kwargs['cid'] = cc.cid
                    break
        if floor != 0 and room == 0: #只选择了楼层没有选择教室
            cids = []
            for cc in ccs:
                if cc.classroom_name//100 == floor:
                    cids.append(cc.cid)
            kwargs['cid__in'] = cids
        if floor == 0 and room != 0: #只选择了教室没有选择楼层
            cids = []
            for cc in ccs:
                if cc.classroom_name%10 == room:
                    cids.append(cc.cid)
            kwargs['cid__in'] = cids
        if week != 0:
            kwargs['week'] = week
        if day != 0:
            kwargs['day'] = day
        if time != 0:
            kwargs['time'] = time
        if state != 0:
            kwargs['state'] = state
        if building==1:#查询的是逸夫楼
            classroom_list=ClassroomuseinfoIf.objects\
                .values("use_id","building_id","cid","week","day","time","state","remark")\
                .filter(**kwargs)
        if building==2:#查询的是机电楼
            classroom_list=ClassroomuseinfoJidian.objects \
                .values("use_id", "building_id", "cid", "week", "day", "time", "state", "remark") \
                .filter(**kwargs)
        if building==3:#查询的是经管楼
            classroom_list=ClassroomuseinfoJingguan.objects \
                .values("use_id", "building_id", "cid", "week", "day", "time", "state", "remark") \
                .filter(**kwargs)
        if building==4:#查询的是外语楼
            classroom_list=ClassroomuseinfoWaiyu.objects \
                .values("use_id", "building_id", "cid", "week", "day", "time", "state", "remark") \
                .filter(**kwargs)

    except:
        return JsonResponse({"flag": "查询出错"})

    data=[]
    id2name = {1: '逸夫楼', 2: '机电楼', 3: '经管楼', 4: '外语楼'}
    for classroom in classroom_list:
        data_dict={}
        cc = Classroombasicinfo.objects.filter(cid=classroom["cid"])[0]
        r = Reserve.objects.filter(classroom_id=classroom["cid"], day=classroom["day"], week=classroom["week"],
                                   time=classroom["time"], user_id=uid).exclude(state=2)

        data_dict['use_id']=classroom["use_id"]
        data_dict["building_id"] = classroom["building_id"]
        data_dict["building_name"] = id2name[classroom["building_id"]]
        data_dict["cid"]= cc.classroom_name
        data_dict["ccid"]= classroom["cid"]
        data_dict["week"]=classroom["week"]
        data_dict["day"]=classroom["day"]
        data_dict["time"]=classroom['time']
        if classroom['state']==1:
            data_dict["state"]='空闲'
        if classroom['state']==2:
            data_dict["state"] = '使用中'
        if len(r) > 0:
            if r[0].state == 1:
                data_dict["state"] = '已预约'
            else:
                data_dict["state"] = '预约中'
        data_dict["capacity"]=cc.capacity
        data.append(data_dict)

    return JsonResponse({
        "code": 0,
        "flag": 0,
        "data": data
    })

def update_useInfo_new(request):
    # 检错
    try:
        use_id = int(request.POST["use_id_in"]) #获取要修改的教室使用信息的索引
        print(use_id)
    except:
        return JsonResponse({"flag": "id错误"})
    try:
        building_id = int(request.POST["building_id_in"]) #获取教室所在的楼栋
        print(building_id)
    except:
        return JsonResponse({"flag": "楼栋信息错误"})
    try:
        update_select=int (request.POST.get('update_select'))
        print(update_select)
    except:
        return JsonResponse({"flag": "请选择教室状态"})
    try:
        update_remark=request.POST.get('update_remark')
        print(update_remark)
    except:
        return JsonResponse({"flag": "请填写教室安排信息"})

    # 更新
    try:
        if building_id == 1:
            ClassroomuseinfoIf.objects.filter(use_id=use_id).update(state=update_select, remark=update_remark)
        if building_id == 2:
            ClassroomuseinfoJidian.objects.filter(use_id=use_id).update(state=update_select, remark=update_remark)
        if building_id == 3:
            ClassroomuseinfoJingguan.objects.filter(use_id=use_id).update(state=update_select, remark=update_remark)
        if building_id == 4:
            ClassroomuseinfoWaiyu.objects.filter(use_id=use_id).update(state=update_select, remark=update_remark)
    except :
        return JsonResponse({"flag": "更新失败"})

    return JsonResponse({"flag": 0})

